package com.translation.assistant.data.bean;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 自定义一个双向的HashMap类
 * 用HashSet存储keys和values
 * 用来做映射表
 */
public class BiHashMap<K,V> {
    private final HashMap<K,V> mKvMap = new HashMap<>();
    private final HashMap<V,K> mVkMap = new HashMap<>();

    public int size() {
        return mKvMap.size();
    }

    public boolean isEmpty() {
        return mKvMap.isEmpty();
    }

    public boolean containsKey(@Nullable Object key) {
        if (key == null)
            return false;
        return mKvMap.containsKey(key);
    }

    public boolean containsValue(@Nullable Object value) {
        if (value == null)
            return false;
        return mVkMap.containsKey(value);
    }

    @Nullable
    public V getValue(@Nullable Object key) {
        if (key == null)
            return null;
        return mKvMap.get(key);
    }

    @Nullable
    public K getKey(@Nullable Object value) {
        if (value == null)
            return null;
        return mVkMap.get(value);
    }

    public void put(K key, V value) {
        mKvMap.put(key,value);
        mVkMap.put(value,key);
    }

    @Nullable
    public V removeByKey(@Nullable Object key) {
        if (!containsKey(key))
            return null;
        V oldValue = mKvMap.remove(key);
        mVkMap.remove(oldValue);
        return oldValue;
    }

    @Nullable
    public K removeByValue(@Nullable Object value) {
        if (!containsValue(value))
            return null;
        K oldKey = mVkMap.remove(value);
        mKvMap.remove(oldKey);
        return oldKey;
    }

    public void putAll(@NonNull Map<? extends K, ? extends V> map) {
        for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
            put(entry.getKey(),entry.getValue());
        }
    }

    public void clear() {
        mKvMap.clear();
        mVkMap.clear();
    }

    @NonNull
    public Set<K> keySet() {
        return mKvMap.keySet();
    }

    @NonNull
    public Set<V> valueSet() {
        return mVkMap.keySet();
    }

    @NonNull
    public Set<Map.Entry<K, V>> entrySet() {
        return mKvMap.entrySet();
    }

}
